package hfuu.com.cn.teasystemapp;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import hfuu.com.cn.teasystemapp.bean.land;
import hfuu.com.cn.teasystemapp.bean.operate;
import hfuu.com.cn.teasystemapp.bean.pick;
import hfuu.com.cn.teasystemapp.bean.role;
import hfuu.com.cn.teasystemapp.bean.tree;
import hfuu.com.cn.teasystemapp.bean.user;
import hfuu.com.cn.teasystemapp.util.HttpUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends Activity
        implements NavigationView.OnNavigationItemSelectedListener {
    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    Intent intent = new Intent();

    private List<role> roleList;

    private List<user> userList;

    private String rolename = "";
    List<land> landlist;


    private FrameLayout frameLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        landlist= new ArrayList<land>();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       // setSupportActionBar(toolbar);
        Intent i = getIntent();
        userList=new ArrayList<user>();
        String u = i.getStringExtra("username");
        roleList = (List<role>) i.getSerializableExtra("role");
        HttpUtils.doGet("user/userlistad", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res=response.body().string();
                Gson gson=new Gson();
                userList=(List<user>) gson.fromJson(res,new TypeToken<List<user>>() {}.getType());
            }
        });


        HttpUtils.doGet("land/listandroid", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
               // Log.i("re", res);
                landlist = parseJSONWithGSON(res, landlist);
                //System.out.print(landlist.size());
            // Log.i("size",""+landlist.size());
 
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        FrameLayout frameLayout= (FrameLayout) this.findViewById(R.id.content_frame);
        ImageView imageView1= (ImageView) frameLayout.findViewById(R.id.xj);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCameraUseable();
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent,REQUEST_CODE);
            }
        });
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View view = navigationView.getHeaderView(0);
        TextView tv = (TextView) view.findViewById(R.id.usesname1);
        TextView role = (TextView) view.findViewById(R.id.rolename1);
        tv.setText(u);
        rolename = "";
        for (role r : roleList) {
            if (r.getRoleName().equals("超级管理员")) {
                rolename = "超级管理员";
                break;
            }
            rolename += r.getRoleName();
        }
        role.setText(rolename);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
     /* getMenuInflater().inflate(R.menu.activity_main_drawer,menu);
      menu.add(0,0,0,"z");*/
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
       /* if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        // Handle navigation view item clicks here.
        int id = item.getItemId();
        //frameLayout =new ContentFrameLayout();
        if (id == R.id.land) {
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("种植") >= 0 || rolename.indexOf("茶园") >= 0) {
                // ConstraintLayout constraintLayout=
                HttpUtils.doGet("land/listandroid", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res = response.body().string();
                      //  Log.i("re", res);


                        landlist = parseJSONWithGSON(res, landlist);
                        //System.out.print(landlist.size());
                        //Log.i("size",""+landlist.size());

                        intent.putExtra("11","333");
                        intent.putExtra("landlist", (Serializable) landlist);
                        intent.setClass(MainActivity.this, landactivty.class);

                        startActivity(intent);
                    }
                });

                //landactivty landactivty=new landactivty();
                //getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,landactivty);
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }

        }else if (id == R.id.pick) {
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("种植") >= 0 || rolename.indexOf("茶园") >= 0) {
                HttpUtils.doGet("pick/listad", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res=response.body().string();
                        intent.setClass(MainActivity.this,pickactivity.class);
                        Gson gson=new Gson();
                        List<pick>  pickList=new ArrayList<pick>();
                        pickList=(ArrayList<pick>)gson.fromJson(res,new TypeToken<List<pick>>(){}.getType());
                        intent.putExtra("picklist",(Serializable) pickList);
                        intent.putExtra("userlist",(Serializable)userList);
                        intent.putExtra("landlist", (Serializable) landlist);

                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }
        }else if(id==R.id.tree){
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("种植") >= 0 || rolename.indexOf("茶园") >= 0) {
                HttpUtils.doGet("tree/listad", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res=response.body().string();
                        intent.setClass(MainActivity.this,treeActivity.class);
                        Gson gson=new Gson();
                        List<tree>  treeList=new ArrayList<tree>();
                        treeList=(ArrayList<tree>)gson.fromJson(res,new TypeToken<List<tree>>(){}.getType());
                        intent.putExtra("treelist",(Serializable) treeList);
                        intent.putExtra("userlist",(Serializable)userList);
                        intent.putExtra("landlist", (Serializable) landlist);

                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }
        }else if (id == R.id.loginout) {
            new  AlertDialog.Builder(this)
                    .setTitle("退出" )
                    .setMessage("确定退出登陆？" )
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            intent.setClass(MainActivity.this, Login.class);
                            startActivity(intent);
                            finish();
                        }
                    })
                    .setNegativeButton("否" , null)
                    .show();
        }else if(id==R.id.home){
            onCreate(null);
        }else if(id==R.id.operatesq){
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("加工") >= 0) {
                HttpUtils.doGet("operate/sqlistad", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res=response.body().string();

                        Gson gson=new Gson();
                        List<operate>  sqlist=new ArrayList<operate>();
                        sqlist=(ArrayList<operate>)gson.fromJson(res,new TypeToken<List<operate>>(){}.getType());
                       // Log.i("resresresres",sqlist.toString());
                        intent.setClass(MainActivity.this,operatesqacivity.class);
                        intent.putExtra("operatelist",(Serializable) sqlist);

                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }

        }else if(id==R.id.operatern){
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("加工") >= 0) {
                HttpUtils.doGet("operate/rnlistad", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res=response.body().string();
                        intent.setClass(MainActivity.this,operaternacitivity.class);
                        Gson gson=new Gson();
                        List<operate>  sqlist=new ArrayList<operate>();
                        sqlist=(ArrayList<operate>)gson.fromJson(res,new TypeToken<List<operate>>(){}.getType());
                        intent.putExtra("operatelist",(Serializable) sqlist);
                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }
        }else if(id==R.id.operategz){
            if (rolename.indexOf("超级") >= 0 || rolename.indexOf("加工") >= 0) {
                HttpUtils.doGet("operate/gzlistad", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res=response.body().string();
                        intent.setClass(MainActivity.this,operategzacitivity.class);
                        Gson gson=new Gson();
                        List<operate>  sqlist=new ArrayList<operate>();
                        sqlist=(ArrayList<operate>)gson.fromJson(res,new TypeToken<List<operate>>(){}.getType());
                        intent.putExtra("operatelist",(Serializable) sqlist);

                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(MainActivity.this, "无相关权限访问", Toast.LENGTH_LONG).show();
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public List<land> parseJSONWithGSON(String jsonData, List<land> l) {
        //使用轻量级的Gson解析得到的json
        Gson gson = new Gson();
        l = (ArrayList<land>)gson.fromJson(jsonData, new TypeToken<List<land>>() {}.getType());
        return l;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    //用默认浏览器打开扫描得到的地址
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(result.toString());
                    intent.setData(content_url);
                    startActivity(intent);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }


    public static boolean isCameraUseable() {

        boolean canUse =true;

        Camera mCamera =null;

        try{

            mCamera = Camera.open();

// setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null

            Camera.Parameters mParameters = mCamera.getParameters();

            mCamera.setParameters(mParameters);

        }catch(Exception e) {

            canUse =false;

        }

        if(mCamera !=null) {

            mCamera.release();

        }
        return canUse;

    }
   public void refresh(){

        finish();
        Intent i=new Intent(MainActivity.this,MainActivity.class);
        startActivity(i);
   }


}
